from django.shortcuts import render
import logging
from celery_tasks.sms.tasks import ccp_send_sms_code

logger = logging.getLogger('django')
# Create your views here.
# 图形验证码资源
from django.views import View
from django_redis import get_redis_connection
# 手机验证码资源
import random, re
from django import http
from verifications.libs.captcha.captcha import captcha


# from verifications.libs.yuntongxun.ccp_sms import CCP


# 图片验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        :param request:
        :param mobile:
        :return:
        """
        text, image = captcha.generate_captcha()
        print('验证码：', text)

        # 保存图形验证码
        # 使用配置的redis数据库的别名，创建连接打Redis的对象
        redis_conn = get_redis_connection('verify_code')

        # 设置验证过期时间
        redis_conn.setex('img_%s' % uuid, 300, text)

        # 响应
        return http.HttpResponse(image, content_type='image/jpeg')


# 手机验证码
class SMSCodeView(View):
    """手机验证码"""

    def get(self, request, mobile):

        # 接收参数
        image_code_client = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 校验参数
        if not all([image_code_client, uuid]):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '缺少必传参数'
            },
                status=400)

        # 约束校验
        if not re.match(r'^[a-zA-Z0-9]{4}$', image_code_client):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '图形验证码格式错误'
            }, status=400)
        if not re.match(r'^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$', uuid):
            return http.JsonResponse({
                'code': 400,
                'errmsg': 'uuid错误'
            }, status=400)

        # 创建连接到redis的对象
        redis_conn = get_redis_connection('verify_code')
        # 提取图形验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            # 图形验证码过期或者不存在
            return http.JsonResponse({
                'code': 400,
                'errmsg': '图形验证码失效',
            }, status=400)

        # 删除图形验证码，避免恶意测试图形验证码
        try:
            redis_conn.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)

        # 对比图形验证码
        # bytes 转字符串
        image_code_server = image_code_server.decode()
        # 转小写后比较
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({
                'code': 400,
                'errmsg': '验证码输入错误'
            }, status=400)

        # 生成验证码
        sms_code = '%06d' % random.randrange(0, 999999)
        logger.info(sms_code)

        # TODO:pipeline管道实现操作redis数据库，响应速度快
        pl = redis_conn.pipeline()

        # 判断验证码是否已存在，避免频繁发送
        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return http.JsonResponse({
                'code': 400,
                'errmsg': '发送短信过于频繁'
            }, status=400)
        # redis_conn.setex('sms_flag_%s' % mobile,60,1)
        pl.setex('send_flag_%s' % mobile, 60, 1)

        # 保存短信验证码
        # redis_conn.setex('sm_%s' % mobile,300,sms_code)
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.execute()
        # TODO:pipeline方式到此结束

        # 发送验证码
        # 短信模板
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)

        print('短信验证码:', sms_code)

        # 10. 响应结果
        return http.JsonResponse({
            'code': 0,
            'errmsg': '发送短信成功'
        })
